package com.example.newhabitclock.TimeDown

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.example.newhabitclock.R
import com.example.newhabitclock.databinding.FragmentClockThreeBinding
import java.util.concurrent.TimeUnit

class ClockThreeFragment : Fragment() {
    private var _binding: FragmentClockThreeBinding? = null
    private val binding get() = _binding!!
    private val viewModel: TimeDownViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentClockThreeBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 恢复 UI 状态
        if (viewModel.isRunning.value == true) {
            binding.timePickerContainer.visibility = View.GONE
            binding.timerText.visibility = View.VISIBLE
        }
        // 其他初始化
        setupNumberPickers()
        setupClickListeners()
        setupObservers()
    }

    // 初始化时间选择器
    private fun setupNumberPickers() {
        with(binding) {
            hourPicker.minValue = 0
            hourPicker.maxValue = 23
            minutePicker.minValue = 0
            minutePicker.maxValue = 59
        }
    }

    // 设置按钮点击监听
    private fun setupClickListeners() {
        binding.startButton.setOnClickListener {
            if (viewModel.isPaused.value == true) {
                viewModel.resumeTimer() // 继续已暂停的计时
            } else {
                startNewTimer() // 开始新计时
            }
        }

        binding.pauseButton.setOnClickListener {
            viewModel.pauseTimer()
        }

        binding.resetButton.setOnClickListener {
            viewModel.resetTimer()
            resetUI()
        }
    }

    // 启动新计时逻辑
    private fun startNewTimer() {
        val hours = binding.hourPicker.value
        val minutes = binding.minutePicker.value
        val totalMillis = (hours * 3600L + minutes * 60L) * 1000L

        if (totalMillis > 0) {
            viewModel.startNewTimer(totalMillis)
            binding.timePickerContainer.visibility = View.GONE
            binding.timerText.visibility = View.VISIBLE
        }
    }

    // 观察数据变化
    private fun setupObservers() {
        viewModel.remainingTimeMillis.observe(viewLifecycleOwner) { millis ->
            updateTimerDisplay(millis)
        }

        viewModel.isRunning.observe(viewLifecycleOwner) { isRunning ->
            updateButtonVisibility(isRunning, viewModel.isPaused.value ?: false)
        }

        viewModel.isPaused.observe(viewLifecycleOwner) { isPaused ->
            updateButtonVisibility(viewModel.isRunning.value ?: false, isPaused)
        }
    }

    // 更新计时显示
    private fun updateTimerDisplay(millis: Long) {
        val hours = TimeUnit.MILLISECONDS.toHours(millis)
        val minutes = TimeUnit.MILLISECONDS.toMinutes(millis) % 60
        val seconds = TimeUnit.MILLISECONDS.toSeconds(millis) % 60
        binding.timerText.text = String.format("%02d:%02d:%02d", hours, minutes, seconds)
    }

    // 更新按钮状态
    private fun updateButtonVisibility(isRunning: Boolean, isPaused: Boolean) {
        with(binding) {
            when {
                isRunning -> { // 运行中
                    startButton.visibility = View.GONE
                    pauseButton.visibility = View.VISIBLE
                    resetButton.visibility = View.VISIBLE
                }
                isPaused -> { // 暂停状态
                    startButton.text = "开始"
                    startButton.visibility = View.VISIBLE
                    pauseButton.visibility = View.GONE
                    resetButton.visibility = View.VISIBLE
                }
                else -> { // 初始/重置状态
                    startButton.text = "开始"
                    startButton.visibility = View.VISIBLE
                    pauseButton.visibility = View.GONE
                    resetButton.visibility = View.GONE
                }
            }
        }
    }

    // 重置UI到初始状态
    private fun resetUI() {
        binding.timePickerContainer.visibility = View.VISIBLE
        binding.timerText.visibility = View.GONE
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}